package org.jetnuke.modules.news;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URL;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.jetnuke.common.ActionForward;
import org.jetnuke.common.IAction;
import org.jetnuke.common.IAdminInfo;
import org.jetnuke.common.IModuleInfo;
import org.jetnuke.common.IUserInfo;
import org.jetnuke.util.JetUtil;

import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.fetcher.FeedFetcher;
import com.sun.syndication.fetcher.impl.HashMapFeedInfoCache;
import com.sun.syndication.fetcher.impl.HttpURLFeedFetcher;

public class RssRead implements IAction {
	private final static Logger s_log = Logger.getLogger(RssRead.class);
	String  url;

	public void setUrl(String url) {
		this.url = url;
	}

	public static FeedFetcher feedFetcher=new HttpURLFeedFetcher(HashMapFeedInfoCache.getInstance());
	public ActionForward exec(HttpServletRequest request,
			HttpServletResponse response, VelocityContext vc, IModuleInfo info,
			String op, IUserInfo ui, IAdminInfo ai) throws Exception {

		
		if(!url.startsWith("http://")){
			if(!url.startsWith("https://")){
				url="http://"+url;
			}
		}
		SyndFeed feed = feedFetcher.retrieveFeed(new URL(url));
	    vc.put("ls",feed.getEntries());
	    if(feed.getImage()!=null)
	    	vc.put("image",feed.getImage().getUrl());
	    vc.put("description",feed.getDescription());
	    vc.put("site",feed.getLink());
				
		StringWriter sw = new StringWriter(1024 * 4);
		try {
			Template t = Velocity.getTemplate("blocks/RssNews/rss.js");
			t.merge(vc, sw);
		} catch (Exception e) {
			s_log.error(e);
		}
		JetUtil.manageReponseCookies(vc,response);
		response.setContentType("application/x-javascript");
		String txt = sw.toString();
		
		PrintWriter pw = response.getWriter();
		pw.write(txt);
		return null;
	}

}
